package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.commom.R;
import com.itheima.ydd.entity.YddLink;
import com.itheima.ydd.mapper.YddLinkMapper;
import com.itheima.ydd.service.YddLinkService;
import com.itheima.ydd.utils.PageUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 友情链接
 */
@RestController
@RequestMapping("ydd_link")
@Slf4j
public class YddListController {
    @Autowired
    private YddLinkService yddLinkService;

    /**
     * 链接详情
     *
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public R getUserById(Integer id) {
        log.info("根据id查询用户信息");
        YddLink yddLink = yddLinkService.getById(id);
        if (yddLink != null) {
            return R.success("", yddLink);
        } else {
            return R.error("没有查询到对应的用户信息");
        }
    }

    /**
     * 分页查询
     *
     * @param page
     * @param limit
     * @return
     */
    @GetMapping("/list")
    public R page(Integer page, Integer limit, String type) {
        log.info("page={},limit={},type={}", page, limit, type);
        Page<YddLink> pageInfo = new Page<>(page, limit);

        LambdaQueryWrapper<YddLink> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(type), YddLink::getType, type);

        yddLinkService.page(pageInfo, queryWrapper);
        List<YddLink> records = pageInfo.getRecords();

        PageUtils<YddLink> pageUtils = new PageUtils<>(pageInfo, records);
        return R.success(" ", pageUtils);
    }

    /**
     * 添加链接
     *
     * @param yddLink
     * @return
     */
    @PostMapping("/add")
    public R save(@RequestBody YddLink yddLink) {
        log.info("yddLink:{}", yddLink.toString());
        yddLinkService.save(yddLink);
        return R.success("添加成功", yddLink);
    }

    /**
     * 根据ID进行链接删除
     *
     * @param id
     * @return
     */
    @GetMapping("/del")
    public R deleteById(Integer id) {
        yddLinkService.removeById(id);
        return R.success("删除成功", id);
    }

    /**
     * 根据ID进行链接修改
     *
     * @param yddLink
     * @return
     */
    @PostMapping("/update")
    public R update(@RequestBody YddLink yddLink) {
        yddLinkService.updateById(yddLink);
        return R.success("修改成功", yddLink);
    }
}
